/**
 * Copyright (c) 2011, University of North Carolina, Chapel Hill

 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, 
 are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this list of 
     conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice, this list 
     of conditions and the following disclaimer in the documentation and/or other materials 
     provided with the distribution.

 * Neither the name of the University of North Carolina at Chapel Hill nor the names of 
     its contributors may be used to endorse or promote  products derived from this 
     software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT   
 OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 */
package edu.unc.ils.memai.extract;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;

import maui.util.Candidate;


/**
 * Implements the phrase extraction algorithm used by the KEA++ library.
 * This implementation is based on kea.KEAFilter.getPhrases
 */
public class MauiCandidateExtractor extends CandidateExtractor
{
    /**
     * Expects an empty hashtable. Fills the hashtable with the candidate
     * keyphrases Stores the position, the number of occurences, and the most
     * commonly occurring orgininal version of each candidate in the Candidate
     * object.
     *
     * Returns the total number of words in the document.
     *
     * @throws Exception
     */
    public HashMap<String, Candidate> getCandidates(List<String> segments) throws Exception {

        if (debugMode) {
            System.err.println("---- Extracting candidates... ");
        }

        HashMap<String, Candidate> candidatesTable = new HashMap<String, Candidate>();

        String[] buffer = new String[maxPhraseLength];

        // Extracting strings of a predefined length from "str":

        int pos = 0;
        int totalFrequency = 0;
        int firstWord = 0;
        for (String segment: segments)
        {
            String token = segment;

            int numSeen = 0;
            StringTokenizer wordTok = new StringTokenizer(token, " ");

            while (wordTok.hasMoreTokens()) {

                pos++;

                String word = wordTok.nextToken();
                if (stopwords.contains(word.toLowerCase()))
                    continue;

                // Store word in buffer
                for (int i = 0; i < maxPhraseLength - 1; i++) {
                    buffer[i] = buffer[i + 1];
                }
                buffer[maxPhraseLength - 1] = word;
                // How many are buffered?
                numSeen++;
                if (numSeen > maxPhraseLength) {
                    numSeen = maxPhraseLength;
                }

                // Don't consider phrases that end with a stop word
                //      if (!vocabularyName.equals("wikipedia")) {
                if (stopwords.contains(buffer[maxPhraseLength - 1])) {
                    // pos++;
                    continue;
                }
                //      }

                // Loop through buffer and add phrases to hashtable
                StringBuffer phraseBuffer = new StringBuffer();
                for (int i = 1; i <= numSeen; i++) {
                    if (i > 1) {
                        phraseBuffer.insert(0, ' ');
                    }
                    phraseBuffer.insert(0, buffer[maxPhraseLength - i]);

                    // Don't consider phrases that begin with a stop word
                    // In free indexing only
                    //      if (!vocabularyName.equals("wikipedia")) {
                    if ((i > 1)
                            && (stopwords.contains(buffer[maxPhraseLength
                                                          - i]))) {
                        continue;
                    }
                    //}

                    // Only consider phrases with minimum length
                    if (i >= minPhraseLength) {

                        // each detected candidate phase in its original
                        // spelling form
                        String form = phraseBuffer.toString();

                        // list of candidates extracted for a given original
                        // string
                        // in case of term assignment more than one possible!
                        Vector<String> candidateNames = new Vector<String>();

                        //      System.err.println("...retrieving senses for form " + form);
                        // if a controlled vocabulary is used
                        // retrieve its senses
                        for (String sense : vocab.getSenses(form)) {
                            //      System.err.println(form + " (" + vocabulary.getTerm(sense)+"), ");
                            candidateNames.add(sense);
                        }

                        //              System.err.println("...conflating candidates");
                        // ignore all those phrases
                        // that have empty pseudo phrases or
                        // that map to nothing in the vocabulary
                        if (!candidateNames.isEmpty()) {

                            for (String name : candidateNames) {

                                Candidate candidate = candidatesTable.get(name);

                                if (candidate == null) {
                                    // this is the first occurrence of this
                                    // candidate
                                    // create a candidate object
                                    firstWord = pos - i;
                                    candidate = new Candidate(name, form,
                                            firstWord);
                                    totalFrequency++;
                                    
                                    String term = vocab.getTerm(name);
                                    // if it's a controlled vocabulary, this allows
                                    // retrieve how this topic is refered to by a descriptor
                                    candidate.setTitle(term);
                                    
                                    //System.out.println(term + ", " + form + ", " + firstWord + ", " + name);

                                } else {

                                    // candidate has been observed before
                                    // update its values
                                    // System.out.println(form);
                                    firstWord = pos - i;
                                    candidate.recordOccurrence(form, firstWord);
                                    totalFrequency++;
                                    
                                    //System.out.println(candidate.getTitle() + ", " + form + ", " + firstWord + ", " + candidate.getFrequency() + ", " +  name);
                                }
                                if (candidate != null) {
                                    candidatesTable.put(name, candidate);
                                }
                            }
                        }
                    }
                }
            }
        }

        Set<String> keys = new HashSet<String>();
        keys.addAll(candidatesTable.keySet());
        for (String key : keys) {
            Candidate candidate = candidatesTable.get(key);
            if (candidate.getFrequency() < minOccurFrequency)
                candidatesTable.remove(key);
            else
                candidate.normalize(totalFrequency, pos);
        }

        return candidatesTable;
    }
}

